import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { createHtmlPlugin } from "vite-plugin-html";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";

const getTarget = (mode, target) => {
  return loadEnv(mode, process.cwd())[target];
};

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  return {
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "src"),
        "~@": path.resolve(__dirname, "src"),
      },
      // 自动解析的扩展名
      extensions: [".js", ".vue"],
    },
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: {},
          javascriptEnabled: true,
        },
        scss: {
          api: "modern-compiler", // or 'modern'
        },
      },
    },
    base: mode === "production" ? "/dist/" : "/",
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
      createHtmlPlugin({
        inject: {
          data: {
            //获取标题变量
            title: getTarget(mode, "VITE_APP_TITLE"),
          },
        },
      }),
    ],
    build: {
      /** If you set esmExternals to true, this plugins assumes that
        all external dependencies are ES modules */

      commonjsOptions: {
        esmExternals: true,
      },
    },
  };
});
